//
//  SYWebViewController.m
//  songyao
//
//  Created by work on 16/11/14.
//  Copyright © 2016年 saikuo. All rights reserved.
//

#import "SYWebViewController.h"
#import "CustomNavController.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
//#import "UIViewController+XMGExtension.h"


@interface SYWebViewController () <UIWebViewDelegate,NJKWebViewProgressDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate> {
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
}

@property (nonatomic,strong) UIWebView  *webView;

@end

@implementation SYWebViewController

- (void)setIsTopHidden:(BOOL)isTopHidden {
    _isTopHidden = isTopHidden;
}


- (void)actionBack:(id)sender {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    } else
        [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    if (_isTopHidden) {
        self.fd_prefersNavigationBarHidden = YES;
    }
    [self createNavigationBackItem];
//    [self createLeftTwoNavigationItem:[UIImage imageNamed:@"navigationButtonClose"]];
    [self createNavigationRightImageItem:[UIImage imageNamed:@"navigationButtonClose"]];
    
    self.webView = [[UIWebView alloc] init];
    [self.view addSubview:self.webView];
    
    _progressProxy = [[NJKWebViewProgress alloc] init];
    self.webView.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(self.view);
    }];

    if (_requestUrl) {
        [self.webView loadRequest:[NSURLRequest requestWithURL:_requestUrl]];
    } else if (_orderId) {
        WS(weakSelf);
        _progressView.hidden = YES;
        [_progressView removeFromSuperview];
        [SVProgressHUD showWithStatus:@"正在加载"];
        
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:_progressView];
    NSString *str = [Tool getFileCache:PRODUCTDETAILPREKEY];
    if (str && [[_requestUrl absoluteString] hasPrefix:str]) {
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_progressView removeFromSuperview];
    [SVProgressHUD dismiss];
    NSString *str = [Tool getFileCache:PRODUCTDETAILPREKEY];
    if (str && [[_requestUrl absoluteString] hasPrefix:str]) {
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
//    }
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
//    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
//    }

}

- (void)setRequestUrl:(NSURL *)requestUrl {
    _requestUrl = requestUrl;
}

#pragma mark - delegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"title==%@",title);
    self.title = title;
//    NSString *javascript = [NSString stringWithFormat:@"var viewPortTag=document.createElement('meta');  \
//                  viewPortTag.id='viewport';  \
//                  viewPortTag.name = 'viewport';  \
//                  viewPortTag.content = 'width=%d; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;';  \
//                  document.getElementsByTagName('head')[0].appendChild(viewPortTag);" , (int)webView.bounds.size.width];
//    
//    [webView stringByEvaluatingJavaScriptFromString:javascript];
    
//    CGSize contentSize = webView.scrollView.contentSize;
//    CGSize viewSize = self.view.bounds.size;
//    
//    float rw = viewSize.width / contentSize.width;
//    
//    webView.scrollView.minimumZoomScale = rw;
//    webView.scrollView.maximumZoomScale = rw;
//    webView.scrollView.zoomScale = rw;
    
//    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
//    [webView stringByEvaluatingJavaScriptFromString:meta];
}

- (void)actionNavigationRightItem:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)actionLeftTwoItem:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress {
    [_progressView setProgress:progress animated:YES];
    self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSURL *url = [request URL];
    if ([[url scheme] isEqualToString:@"naxiastore"]) {
        NSDictionary *paramss = [self getParams:[url query]];
        NSString *params = @"";
        if ([paramss objectForKey:@"data"]) {
            params = [Tool URLDecodedString:[paramss objectForKey:@"data"]];
        }
        
        switch ([[paramss objectForKey:@"action"] integerValue]) {
            
        }
        return NO;
    }
    return YES;
}


- (NSDictionary *)getParams:(NSString *)str {
    __block NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (str.length) {
        NSArray *array = [str componentsSeparatedByString:@"&"];
        if (array.count) {
            [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *str = array[idx];
                NSArray *array = [str componentsSeparatedByString:@"="];
                if (array.count > 1) {
                    [dic setObject:array[1] forKey:array[0]];
                }
            }];
        }
    }
    return dic;
}


- (void)webViewDidStartLoad:(UIWebView *)webView {
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
//    [SVProgressHUD showErrorWithStatus:@"加载失败"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

